package com.zrrd.yt.order.controller;

import com.zrrd.yt.cart.client.CartFeignClient;
import com.zrrd.yt.common.result.Result;
import com.zrrd.yt.common.util.AuthContextHolder;
import com.zrrd.yt.model.cart.CartInfo;
import com.zrrd.yt.model.order.OrderDetail;
import com.zrrd.yt.model.order.OrderInfo;
import com.zrrd.yt.model.user.UserAddress;
import com.zrrd.yt.order.service.OrderService;
import com.zrrd.yt.product.client.ProductFeigClient;
import com.zrrd.yt.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/order/auth")
public class OrderApiController {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private ProductFeigClient productFeigClient;
    @Autowired
    private OrderService orderService;

    //订单结算
    @GetMapping("/trade")
    public Result<Map> trade(HttpServletRequest request) {
        //获取用户ID
        String userId = AuthContextHolder.getUserId(request);
        //创建最终返回的Map集合
        Map<String, Object> map = new HashMap<>();
        //获取用户地址信息
        List<UserAddress> userAddresses = userFeignClient.findUserAddressByUserId(userId);
        //获取用户选中购物车数据信息
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        //创建订单明细集合
        List<OrderDetail> detailList = new ArrayList<>();
        //将购物车的数据转换后存入订单明细集合
        for (CartInfo cartInfo : cartCheckedList) {
            OrderDetail detail = new OrderDetail();
            detail.setSkuId(cartInfo.getSkuId());
            detail.setSkuName(cartInfo.getSkuName());
            detail.setSkuNum(cartInfo.getSkuNum());
            detail.setOrderPrice(cartInfo.getSkuPrice());
            detail.setImgUrl(cartInfo.getImgUrl());
            detailList.add(detail);
        }
        //计算订单总金额
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailList);
        orderInfo.sumTotalAmount();

        //获取流水号
        String tradeNo = orderService.getTradeNo(userId);

        //存入Map集合
        map.put("userAddressList", userAddresses);
        map.put("detailArrayList", detailList);
        map.put("totalNum", detailList.size());
        map.put("totalAmount", orderInfo.getTotalAmount());
        map.put("tradeNo", tradeNo);
        //返回
        return Result.ok(map);
    }

    //提交订单
    @PostMapping("/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        //设置用户ID
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //根据请求对象获取流水号参数
        String tradeNo = request.getParameter("tradeNo");
        //校验流水号
        boolean checkTradeNo = orderService.checkTradeNo(userId, tradeNo);
        if (!checkTradeNo) {
            return Result.fail().message("不能提交重复的订单");
        }
        //删除流水号
        orderService.deleteTradeNo(userId);
        //获取订单明细
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail detail : orderDetailList) {
            //校验库存
            boolean checkStock = orderService.checkStock(detail.getSkuId(), detail.getSkuNum());
            if (!checkStock) {
                return Result.fail().message(detail.getSkuName() + "库存不足");
            }
            //校验价格
            BigDecimal skuPrice = productFeigClient.getSkuPrice(detail.getSkuId());
            System.out.println("获取的最新价格====>"+skuPrice);
            System.out.println("订单明细的商品价格====>"+detail.getOrderPrice());
            if(detail.getOrderPrice().compareTo(skuPrice) != 0){
                //重新更新最新价格
                cartFeignClient.loadCartData(userId);
                return Result.fail().message(detail.getSkuName() + "价格有变动，请刷新页面重试");
            }
        }
        //调用业务层提交订单
        Long orderId = orderService.saveOrderInfo(orderInfo);
        //返回结果
        return Result.ok(orderId);
    }

}
